<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\User as UserModel;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'profitOrder', 'team_record', 'certificate', 'order_data'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account  = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile    = $this->request->post('mobile');
        $captcha   = $this->request->post('captcha');
        $parent_id = $this->request->request('parent_user_id');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $parent_data = UserModel::where(['id' => $parent_id])->find();
        if ($parent_data) {
            $parent_user_id = $parent_data['id'];
        } else {
            $parent_user_id = 0;
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            if ($user->parent_user_id == 0 && $parent_user_id > 0) {
                Db::name('user')->where('id', $user->id)->update(['parent_user_id' => $parent_user_id]);
                //邀请奖励
                if (config("site.parent_give") > 0) {
                    \app\common\model\User::score(config("site.parent_give"), $parent_user_id, '邀请奖励');
                }
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username       = $this->request->post('username');
        $password       = $this->request->post('password');
        $email          = $this->request->post('email');
        $mobile         = $this->request->post('mobile');
        $code           = $this->request->post('code');
        $parent_user_id = $this->request->request('parent_user_id');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, [], $parent_user_id);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user     = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio      = $this->request->post('bio');
        $avatar   = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio    = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user    = $this->auth->getUser();
        $email   = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification        = $user->verification;
        $verification->email = 1;
        $user->verification  = $verification;
        $user->email         = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        if (!$user) {
            $this->error(__('请先登录'));
        }
        $mobile  = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        /* $result = Sms::check($mobile, $captcha, 'changemobile');
         if (!$result) {
             $this->error(__('Captcha is incorrect'));
         }*/
        $verification         = $user->verification;
        $verification->mobile = 1;
        $user->verification   = $verification;
        $user->mobile         = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url      = url('user/index');
        $platform = $this->request->post("platform");
        $code     = $this->request->post("code");
        $config   = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type        = $this->request->post("type", 'mobile');
        $mobile      = $this->request->post("mobile");
        $email       = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha     = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $oldpassword 旧密码
     * @param string $newpassword 新密码
     */
    public function resetpassword()
    {
        $oldpassword = $this->request->post("oldpassword");
        $newpassword = $this->request->post("newpassword");
        if (!$newpassword || !$oldpassword) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->changepwd($newpassword, $oldpassword);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取团队长一二级人员数 订单数  订单金额
     */
    public function team_data()
    {
        $user_id   = $this->auth->id;
        $user_data = Db::name("user")->where(['id' => $user_id, 'team' => 1])->field("one_team_sum,two_team_sum,one_order_sum,two_order_sum,one_order_money,two_order_money")->find();
        if (!$user_data) {
            $this->error("当前用户不是团队长！");
        }
        $son_data = Db::name("user")->where(['parent_user_id' => $user_id])->select();
        foreach ($son_data as $k => $v) {

                $son_data[$k]['createtime'] = date('Y-m-d H:i:s', $v['createtime']);

        }
        $user_data['son_data'] = $son_data;//下级人员
        $order_time = $this->request->post("order_time");
        if($order_time){
            $str_time = self::getMonthRange($order_time);
            $end_time = self::getMonthRange($order_time,false);
            $w['t.createtime'] = ['between', [$str_time, $end_time]];
        }
        $w['t.user_id']        = $user_id;
        $config                = get_addon_config('alioss');
        $order_data            = Db::name("order_team_user t")->join('shop_order ar', 't.order_id=ar.id')->join('user u', 't.user_id=u.id')->where($w)->field("t.money,t.createtime,ar.order_sn,u.nickname,u.avatar")->select();
        $sum_money = 0;
        foreach ($order_data as $k => $v) {
            if ($v['avatar']) {
                //$order_data[$k]['avatar'] = $config['cdnurl'] . $v['avatar'];
            }
            $order_data[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
            $d = Db::name("shop_order_goods")->where(['order_sn'=>$v['order_sn']])->find();
            $goods_name = Db::name("shop_goods")->where(['id'=>$d['goods_id']])->value('title');
            $image = Db::name("shop_goods")->where(['id'=>$d['goods_id']])->value('image');
            $order_data[$k]['goods_name'] = $goods_name;
            $order_data[$k]['image'] = $config['cdnurl'] . $image;
            $sum_money = $sum_money+$v['money'];
        }
        $user_data['order_data'] = $order_data;//订单
        $user_data['sum_money'] = $sum_money;
        $this->success('成功', $user_data);
    }
    private function getMonthRange( $date, $returnFirstDay = true ) {

        $timestamp = strtotime( $date );

        if ( $returnFirstDay ) {

            $monthFirstDay = strtotime(date( 'Y-m-1 00:00:00', $timestamp ));

            return $monthFirstDay;

        } else {

            $mdays = date( 't', $timestamp );

            $monthLastDay = strtotime(date( 'Y-m-' . $mdays . ' 23:59:59', $timestamp ));

            return $monthLastDay;

        }

    }
    public function team_apply()
    {
        $user_id   = $this->auth->id;
        $real_name = $this->request->post("real_name");
        $tel       = $this->request->post("tel");
        $img       = $this->request->post("img");
        if (!$real_name || !$tel || !$img) {
            $this->error("缺少必传参数！");
        }
        $in_data['uid']        = $user_id;
        $in_data['real_name']  = $real_name;
        $in_data['tel']        = $tel;
        $in_data['img']        = $img;
        $in_data['createtime'] = time();
        $in_data['updatetime'] = time();
        $in_status             = Db::name("user_team")->insert($in_data);
        if ($in_status) {
            $this->success('成功');
        } else {
            $this->error('失败');
        }
    }

    public function pd_user_team()
    {
        $w['uid']    = $this->auth->id;
        $w['status'] = ['in', '0,1'];
        $data        = Db::name("user_team")->where($w)->find();
        if ($data) {
            $this->success('成功', $data);
        } else {
            $this->success('失败');
        }
    }

    /**
     * 收益排行榜
     */
    public function profitOrder()
    {
        $w['profit_money'] = array('>', 0);
        $w['team']         = 1;
        $son_data          = Db::name("user")->where($w)->field("profit_money,username,createtime")->order("profit_money desc")->select();
        $this->success('成功', $son_data);
    }

    /**
     * 我报名的
     */
    public function train_enroll()
    {
        $user_id    = $this->auth->id;
        $w['t.uid'] = $user_id;
        $son_data   = Db::name("train_enroll t")->join('train_article ar', 't.article_id=ar.id')->where($w)->field("ar.*")->select();
        $this->success('成功', $son_data);
    }

    public function team_record()
    {
        $user_id   = $this->auth->id;
        $user_data = Db::name("user")->where(['id' => $user_id, 'team' => 1])->field("profit_money,username,avatar,level")->find();
        if (!$user_data) {
            $this->error("当前用户不是团队长！");
        }
        $one_money_sum           = Db::name("shop_order")->where(['one_uid' => $user_id, 'orderstate' => 0])->sum('one_money');
        $otwo_money_sum          = Db::name("shop_order")->where(['two_uid' => $user_id, 'orderstate' => 0])->sum('two_money');
        $amount_sum              = Db::name("shop_order")->where(['user_id' => $user_id, 'orderstate' => 3])->sum('amount');
        $re_data['level']        = $user_data['level'];
        $re_data['avatar']       = $user_data['avatar'];
        $re_data['username']     = $user_data['username'];
        $re_data['profit_money'] = $user_data['profit_money'];
        $re_data['money_sum']    = $one_money_sum + $otwo_money_sum;
        $re_data['amount_sum']   = $amount_sum;
        $this->success('成功', $re_data);
    }

    /**
     * 站内信
     */
    public function mail()
    {
        $user_id   = $this->auth->id;
        $mail_data = Db::name("mail")->where(['uid' => $user_id])->select();
        $this->success('成功', $mail_data);
    }

    /**
     * @return void
     * 证书查找
     */
    public function certificate()
    {
        $code        = $this->request->post("code");
        $file_code   = $this->request->post("file_code");
        $where['id'] = array('>', 0);
        if ($code) {
            $where['code'] = array('like', $code);
        }
        if ($file_code) {
            $where['file_code'] = array('like', $file_code);
        }
        $re_data = Db::name("certificate")->where($where)->select();
        $this->success('成功', $re_data);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 提现数据
     */
    public function withdrawal()
    {
        $user_id                 = $this->auth->id;
        $user_data               = Db::name("user")->where(['id' => $user_id, 'team' => 1])->field("profit_money,username,avatar,level,money")->find();
        $amount_sum              = Db::name("shop_order")->where(['user_id' => $user_id, 'orderstate' => 3])->sum('amount');
        $user_data['amount_sum'] = $amount_sum;
        $w_data                  = Db::name("user_money_log")->where(['user_id' => $user_id, 'status' => 2])->select();
        $user_data['w_data']     = $w_data;
        $this->success('成功', $user_data);
    }

    /**
     * @return void
     * 绑定银行卡
     */
    public function user_bank()
    {
        $user_id      = $this->auth->id;
        $bank_name    = $this->request->post('bank_name');
        $bank_deposit = $this->request->post('bank_deposit');
        $bank_code    = $this->request->post('bank_code');
        $user_name    = $this->request->post('user_name');
        if (!$bank_name || !$bank_deposit || !$bank_code || !$user_name) {
            $this->error("缺少必传参数！");
        }
        $in_arr['uid']          = $user_id;
        $in_arr['bank_name']    = $bank_name;
        $in_arr['bank_deposit'] = $bank_deposit;
        $in_arr['bank_code']    = $bank_code;
        $in_arr['user_name']    = $user_name;
        $in_arr['createtime']   = time();
        $add1                   = Db::name("society")->insert($in_arr);
        if ($add1) {
            $this->success('成功');
        } else {
            $this->error("失败");
        }
    }

    /**
     * @return void
     * 绑定银行卡
     */
    public function withdrawal_add()
    {
        $user_id = $this->auth->id;
        $money   = $this->request->post('money');

        if (!$money) {
            $this->error("缺少必传参数！");
        }
        $in_arr['uid']   = $user_id;
        $in_arr['money'] = $money;
        $bank_data       = Db::name("society")->where(['uid' => $user_id])->find();
        if (!$bank_data) $this->error("请先绑定银行卡！");
        $in_arr['bank_id']    = $bank_data['id'];
        $in_arr['createtime'] = time();
        $add1                 = Db::name("withdrawal")->insert($in_arr);
        if ($add1) {
            $this->success('成功');
        } else {
            $this->error("失败");
        }
    }

    public function share_add()
    {
        $user_id                = $this->auth->id;
        $type                   = $this->request->post('type');
        $remarks                = $this->request->post('remarks');
        $add_data['uid']        = $user_id;
        $add_data['type']       = $type;
        $add_data['remarks']    = $remarks;
        $add_data['createtime'] = time();
        $add_data['updatetime'] = time();
        $add1                   = Db::name("share")->insert($add_data);
        if ($add1) {
            $this->success('成功');
        } else {
            $this->error("失败");
        }
    }

    public function share_list()
    {
        $user_id  = $this->auth->id;
        $w['uid'] = $user_id;
        $type     = $this->request->post('type');
        if ($type) {
            $w['type'] = $type;
        }
        $list   = Db::name("share")->where($w)->select();
        $config = get_addon_config('alioss');
        foreach ($list as $k => $v) {
            $u_data               = Db::name('user')
                ->where(['id' => $v['uid']])
                ->find();
            $list[$k]['nickname'] = $u_data['nickname'];
            if ($u_data['avatar']) {
                $list[$k]['avatar'] = $config['cdnurl'] . $u_data['avatar'];
            } else {
                $list[$k]['avatar'] = '';
            }

        }
        $this->success('成功', $list);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function order_data()
    {
        $user_id  = $this->auth->id;
        $str_time = strtotime($this->request->post('str_time'));
        $end_time = strtotime($this->request->post('end_time'));
        if ($str_time) {
            $w['t.createtime'] = array('>=', $str_time);
        }
        if ($end_time) {
            $w['t.createtime'] = array('<=', $end_time);
        }
        if ($end_time && $str_time) {
            $w['t.createtime'] = array('between', [$str_time, $end_time]);
        }
        $sum_money      = 0;
        $w['t.user_id'] = $user_id;
        $config         = get_addon_config('alioss');
        $order_data     = Db::name("order_team_user t")
            ->join('shop_order ar', 't.order_id=ar.id')
            ->join('user u', 't.user_id=u.id')
            ->field("t.money,t.createtime,ar.order_sn,u.nickname,u.avatar")
            ->where($w)
            ->select();
        foreach ($order_data as $k => $v) {
            if ($v['avatar']) {
               // $order_data[$k]['avatar'] = $config['cdnurl'] . $v['avatar'];
            }
            $order_data[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
            $sum_money += $v['money'];
        }
        $re_arr['sum_money'] = $sum_money;
        $re_arr['list']      = $order_data;

        $this->success('成功', $re_arr);
    }

    public function getUserTeam()
    {
        $w['uid']    = $this->auth->id;
        $w['status'] = ['in', '0,1'];
        $data        = Db::name("user_team")->where($w)->find();
        if ($data) {
            $s['in_status'] = 1;
            $s['status']    = $data['status'];
        } else {
            $s['in_status'] = 0;
            $s['status']    = 0;
        }
        $this->success('成功', $s);
    }
}
